﻿using System;
using System.Collections.Generic;
using Opalis.QuickIntegrationKit;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Collections;

namespace Active_Directory
{
    [OpalisObject("Get Users in Group")]
    public class GetGroupMembership : IOpalisObject
    {
        private ConnectionCredentials credentials;

        [OpalisConfiguration]
        public ConnectionCredentials Credentials
        {
            get { return credentials; }
            set { credentials = value; }
        }

        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("Group LDAP Path").WithDefaultValue("LDAP://cn=GroupName,ou=Container,DC=Contoso,DC=Com");
            designer.AddCorellatedData(typeof(ADObject));
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            String groupDN = request.Inputs["Group LDAP Path"].AsString();
            response.WithFiltering().PublishRange(getGroupMembers(groupDN));
        }

        private IEnumerable<ADObject> getGroupMembers(string groupDN)
        {
            DirectoryEntry ent = new DirectoryEntry(groupDN, credentials.UserName + "@" + credentials.Domain, credentials.Password);
            PropertyValueCollection ValueCollection = ent.Properties["member"];
            foreach (String userDN in ValueCollection)
            {
                yield return new ADObject("LDAP://" + userDN);
            }
            ent.Dispose();
            ent.Close();
        }
    }
}
